﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace ViewMaker.Core.Wpf
{
    /// <summary>
    /// ViewCommandを処理するヘルパーを設定するビヘイビア
    /// </summary>
    public static class ViewCommandBehavior
    {
        public static readonly DependencyProperty HelperProperty = DependencyProperty.RegisterAttached("Helper", typeof(IViewCommandHelper), typeof(ViewCommandBehavior), new PropertyMetadata(HelperCallback));

        public static IViewCommandHelper GetHelper(FrameworkElement obj)
        {
            return (IViewCommandHelper)obj.GetValue(HelperProperty);
        }

        public static void SetHelper(FrameworkElement obj, IViewCommandHelper value)
        {
            obj.SetValue(HelperProperty, value);
        }

        private static void HelperCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var ele = obj as FrameworkElement;
            if (ele != null)
            {
                if (args.OldValue != null)
                {
                    var helper = (IViewCommandHelper)args.OldValue;
                    if (helper != null) helper.Detach();
                }
                if (args.NewValue != null)
                {
                    var helper = (IViewCommandHelper)args.NewValue;
                    if (helper != null) helper.Attach(ele); 
                }
            }
        }
    }

}
